package com.hopes.bizz.risk.gis.helper;

import cn.hutool.core.date.DateUtil;
import com.hopes.bizz.risk.gis.vo.LineStatistics;
import lombok.Setter;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lyb
 * @version 1.0
 * @date 2024/2/23 15:37
 */

@Setter
public class LineStatisticsHelper<T> {

    private Date beginTime;
    private Date endTime;
    private List<T> data;
    private List<String> legendData;
    private Function<T, Date> handlerDateFun;
    private Function<T, String> groupFun;
    private Function<Date, Date> stepFun;
    private Function<Date, String> XDataFun;

    public LineStatistics doStatistics() {
        LineStatistics lineStatistics = new LineStatistics();
        lineStatistics.setLegendData(legendData);
        Map<String, List<Integer>> dataMap = new HashMap<>();
        while (DateUtil.compare(beginTime, endTime) <= 0) {
            Date preDate = beginTime;
            Date nextDate = stepFun.apply(preDate);
            Map<String, List<T>> taskOrgMap = data.stream().filter(t -> {
                Date handlerDate = handlerDateFun.apply(t);
                return DateUtil.compare(preDate, handlerDate) <= 0 && DateUtil.compare(nextDate, handlerDate) > 0;
            }).collect(Collectors.groupingBy(groupFun));
            lineStatistics.addName(XDataFun.apply(beginTime));
            for (String legend : legendData) {
                List<Integer> data = dataMap.get(legend);
                if (Objects.isNull(data)) {
                    data = new ArrayList<>();
                }
                data.add(Optional.ofNullable(taskOrgMap.get(legend)).map(List::size).orElse(0));
                dataMap.put(legend, data);
            }
            beginTime = nextDate;
        }
        dataMap.forEach(lineStatistics::addData);
        return lineStatistics;
    }


}
